package com.example.service.admin;

import com.example.entity.Admin;
import com.example.entity.DTO.DepartmentDetailDTO;
import com.example.entity.Department;
import com.example.exception.CustomException;
import com.example.mapper.DepartmentMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DepartmentService {
    @Resource
    private DepartmentMapper departmentMapper;

    public List<DepartmentDetailDTO> selectAllDept(String name) {
        return departmentMapper.selectAllDeptByName(name);
    }

    public void addDept(Department department) {
        String name = department.getName();
        Department dbDepartment = departmentMapper.selectByName(name);
        if(dbDepartment != null) {
            throw new CustomException("500", "学院名称已存在!");
        }
        departmentMapper.insert(department);
    }

    public void updateDept(Department department) {
        Integer id = department.getId();
        Department dbDepartment = departmentMapper.selectById(id);
        if(dbDepartment == null) {
            throw new CustomException("500", "学院ID不存在!");
        }
        String dbName = dbDepartment.getName();
        String name = department.getName();
        dbDepartment = departmentMapper.selectByName(name);
        if(dbDepartment != null && !dbName.equals(name)) {
            throw new CustomException("500", "学院名称已存在!");
        }
        departmentMapper.updateById(department);
    }

    public void deleteDept(Integer id) {
        departmentMapper.deleteById(id);
    }

    public DepartmentDetailDTO selectDept(String name) {
        return departmentMapper.selectDeptByName(name);
    }
}
